<template>
  <div class="cart">
    <van-nav-bar title="购物车" />
    <div class="content">
      <van-swipe-cell v-for="(item,index) in cartList" :key="index">
        <input type="checkbox" v-model="item.check" @change="check">
        <img :src="item.img" alt="">
        <section>
          <h5>{{item.name}}</h5>
          <p>
            <span>￥{{item.price}}</span>
            <van-stepper v-model="item.buyNum" />
          </p>
        </section>
        <template #right>
          <van-button square type="danger" @click="$store.commit('delect',index)" text="删除" />
        </template>
      </van-swipe-cell>
    </div>
    <div class="foot">
      <span class="left"><input type="checkbox" v-model="allCheck" @change="$store.commit('checkAll',allCheck)"> 全选</span>
      <span>合计：{{all.price}}</span>
      <span class="right">结算（{{all.num}}）</span>
    </div>
  </div>
</template>

<script>
import { ref, reactive, toRefs,computed } from "vue";
import { useStore } from 'vuex';
export default {
  setup() {
    const { state } = useStore();
    const data = reactive({
      cartList:computed(()=> state.cart),
      allCheck: state.cart.every(item => item.check),
      all: computed(() => {
        let num = 0,price = 0;
        state.cart.forEach(item => {
          if(item.check){
            num+=item.buyNum;
            price+=item.buyNum*item.price;
          }
        })
        return {num:num,price:price }
      })
    })
    const check = () => {
      data.allCheck = data.cartList.every(item => item.check);
    }
    return{
      ...toRefs(data),
      check
    }
  },
};
</script>
<style lang="scss" scoped>
.content {
  height: calc(100% - 96px);
  overflow: auto;
  :deep(.van-swipe-cell__wrapper){
    display: flex;
    align-items: center;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
    .van-button{
      height: 100%;
    }
    img{
      width: 60px;
      margin: 0 10px;
    }
    section{
      flex: 1;
      span{
        color: red;
      }
      .van-stepper{
        float: right;
      }
    }
  }
}
.foot{
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .left{
    margin-left: 10px;
  }
  .right{
    background: red;
    color: #fff;
    padding: 0 10px;
    line-height: 50px;
  }
}
</style>